package com.bml.architect.netty.serialiable;

import com.bml.architect.netty.serialiable.codec.MsgProtoDecoder;
import com.bml.architect.netty.serialiable.codec.MsgProtoEncoder;
import com.bml.architect.netty.serialiable.codec.ProtostuffDecoder;
import com.bml.architect.netty.serialiable.codec.ProtostuffEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolver;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

public class NettySerialServer {

    public static void main(String[] args) {
        EventLoopGroup boss = new NioEventLoopGroup(1);
        EventLoopGroup work = new NioEventLoopGroup();


        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boss, work)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024).
                    childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                   // pipeline.addLast(new ObjectDecoder(10240, ClassResolvers.cacheDisabled(null)));
                    //pipeline.addLast(new ObjectEncoder());
                   // pipeline.addLast(new ProtostuffDecoder());
                   // pipeline.addLast(new ProtostuffEncoder());
                    pipeline.addLast(new MsgProtoEncoder());
                    pipeline.addLast(new MsgProtoDecoder());
                    pipeline.addLast(new SerialServerHandler());
                }
            });
            System.out.println("服务端启动完成...");
            ChannelFuture sync = bootstrap.bind(9000).sync();
            sync.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            boss.shutdownGracefully();
            work.shutdownGracefully();
        }

    }
}
